import React, { useState, useCallback, useRef } from 'react';
import {
  StyleSheet,
  RefreshControl,
  Platform,
  ActivityIndicator,
  FlatList,
  Animated,
  Dimensions,
  TouchableOpacity,
} from 'react-native';
import { Text, View } from '@/components/Themed';
import { FontAwesome } from '@expo/vector-icons';
import Colors from '@/constants/Colors';

// 模拟监控数据接口
interface MonitorData {
  id: string;
  title: string;
  value: number;
  status: 'normal' | 'warning' | 'error';
  timestamp: string;
}

// 骨架屏组件
// 定义一个SkeletonItem组件
const SkeletonItem = () => (
  // 使用View组件包裹
  <View style={styles.skeletonItem}>
    {/* // 使用Animated.View组件包裹 */}
    <Animated.View style={styles.skeletonAnimation} />
  </View>
);

export default function MonitorScreen() {
  // 定义状态变量
  const [data, setData] = useState<MonitorData[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  // 动画值
  const fadeAnim = useRef(new Animated.Value(0)).current;

  // 模拟获取数据
  const fetchData = useCallback(async (isRefresh = false) => {
    if (isRefresh) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }

    try {
      // 模拟API请求延迟
      await new Promise((resolve) => setTimeout(resolve, 1000));

      const newData: MonitorData[] = Array(20)
        .fill(0)
        .map((_, index) => ({
          id: `${Date.now()}-${index}`,
          title: `监控项 ${index + 1}`,
          value: Math.floor(Math.random() * 100),
          status: ['normal', 'warning', 'error'][Math.floor(Math.random() * 3)] as MonitorData['status'],
          timestamp: new Date().toISOString(),
        }));

      if (isRefresh) {
        setData(newData);
      } else {
        setData((prev) => [...prev, ...newData]);
      }
    } finally {
      setRefreshing(false);
      setLoading(false);
      setIsLoading(false);
    }
  }, []);

  // 初始加载
  React.useEffect(() => {
    fetchData();
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true,
    }).start();
  }, []);

  // 渲染监控项
  // 定义一个函数，用于渲染每个监控数据项
  const renderItem = ({ item }: { item: MonitorData }) => {
    // 定义不同状态的颜色
    const statusColors = {
      normal: Colors.light.success,
      warning: Colors.light.warning,
      error: Colors.light.error,
    };

    // 返回一个Animated.View组件，用于渲染每个监控数据项
    return (
      <Animated.View
        style={[
          styles.card,
          { opacity: fadeAnim },
          Platform.select({
            ios: styles.cardIOS,
            android: styles.cardAndroid,
          }),
        ]}
      >
        {/* TouchableOpacity组件，用于点击事件 */}
        <TouchableOpacity style={styles.cardContent} onPress={() => console.log(`Pressed ${item.id}`)}>
          {/* 监控数据项的头部 */}
          <View style={styles.cardHeader}>
            {/* 监控数据项的标题 */}
            <Text style={styles.cardTitle}>{item.title}</Text>
            {/* 监控数据项的状态点 */}
            <View style={[styles.statusDot, { backgroundColor: statusColors[item.status] }]} />
          </View>

          {/* 监控数据项的主体 */}
          <View style={styles.cardBody}>
            {/* 监控数据项的值 */}
            <Text style={styles.valueText}>{item.value}</Text>
            {/* 监控数据项的状态图标 */}
            <FontAwesome
              name={item.status === 'normal' ? 'check-circle' : 'exclamation-circle'}
              size={24}
              color={statusColors[item.status]}
            />
          </View>

          {/* 监控数据项的时间戳 */}
          <Text style={styles.timestamp}>{new Date(item.timestamp).toLocaleTimeString()}</Text>
        </TouchableOpacity>
      </Animated.View>
    );
  };

  // 如果正在加载数据，则显示骨架屏
  if (isLoading) {
    return (
      <View style={styles.container}>
        {Array(5)
          .fill(0)
          .map((_, index) => (
            <SkeletonItem key={index} />
          ))}
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={data}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={() => fetchData(true)} tintColor={Colors.light.tint} />
        }
        onEndReached={() => !loading && fetchData()}
        onEndReachedThreshold={0.5}
        ListFooterComponent={loading ? <ActivityIndicator color={Colors.light.tint} style={styles.loader} /> : null}
        ListEmptyComponent={<Text style={styles.emptyText}>暂无监控数据</Text>}
        contentContainerStyle={styles.list}
        showsVerticalScrollIndicator={false}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  list: {
    padding: 16,
  },
  card: {
    marginBottom: 12,
    borderRadius: 12,
    backgroundColor: '#fff',
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 4,
      },
      android: {
        elevation: 3,
      },
    }),
  },
  cardIOS: {
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  cardAndroid: {
    elevation: 3,
  },
  cardContent: {
    padding: 16,
  },
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  cardTitle: {
    fontSize: 16,
    fontWeight: '600',
  },
  statusDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
  },
  cardBody: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  valueText: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  timestamp: {
    fontSize: 12,
    color: '#666',
  },
  loader: {
    padding: 16,
  },
  emptyText: {
    textAlign: 'center',
    padding: 16,
    color: '#666',
  },
  skeletonItem: {
    height: 120,
    backgroundColor: '#e1e1e1',
    borderRadius: 12,
    marginHorizontal: 16,
    marginVertical: 8,
    overflow: 'hidden',
  },
  skeletonAnimation: {
    height: '100%',
    width: '100%',
    backgroundColor: '#f2f2f2',
  },
});
